/**
 * @author attilax 1466519819@qq.com
 * @version  c0
 * Copyright 2013 attilax reserved.
 * All content (including but not limited to text, pictures, etc.) have copyright restrictions, the note license.
 * all the software source code  copyright belongs to the original owner.
 * Creative Commons protocol use please follow the "sign for non-commercial use consistent"; we do not welcome the large-scale duplication, and all rights reserved.
 * Commercial sites or unauthorized media may not copy software source code.
 **/

package com.mijie.homi.search.api;




import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.log4j.Logger;
import org.logicalcobwebs.proxool.ProxoolException;
import org.logicalcobwebs.proxool.configuration.JAXPConfigurator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


import com.mijie.core.CoreContextLoaderListener;
import com.mijie.homi.common.domain.SearchResult;
import com.mijie.homi.search.dao.mood.MoodDao;
import com.mijie.homi.search.service.index.MoodUserIndexService;
import com.mijie.homi.search.service.index.UserIndexService;
import com.mijie.homi.search.service.mood.MoodService;
import com.mijie.homi.search.util.god;
import com.mijie.query.fulltxtControllor4invoke;
import com.mijie.util.IOUtil;

@Controller
@RequestMapping("/user")
/**
 * @author attilax 1466519819@qq.com
 * @version  c0
 **/
public class UserSearchApi {

	public static final String PROXOOL_XML = "C:\\Users\\Administrator\\Workspaces\\MyEclipse 8.5\\homiSearchServer\\resource\\proxool.xml";
	@Autowired
	private UserIndexService service;
	@Autowired  @Qualifier("moodUserIndexService")
	private MoodUserIndexService moodUserService;

	private Logger logger = Logger.getLogger(this.getClass());

	@RequestMapping(value = "/search", method = RequestMethod.GET)
	/**
	 * @author attilax 1466519819@qq.com
	 * @version  c0
	 **/
	public void search(String idxf, int offset, int limit, String keyword,
			HttpServletResponse response) throws Exception {
		SearchResult result = service.search(idxf, offset, limit, keyword);
		IOUtil.write(response, result.toJSON());
	}

	@RequestMapping(value = "/index", method = RequestMethod.GET)
	/**
	 * @author attilax 1466519819@qq.com
	 * @version  c0
	 **/
	public @ResponseBody
	void RAMIndex(int userId, String nickName) {
		service.RAMIndex(userId, nickName);
	}

	@RequestMapping(value = "/match", method = RequestMethod.GET)
	/**
	 * @author attilax 1466519819@qq.com
	 * @version  c0
	 **/
	public void match(String idxf, int offset, int limit, int userId,
			int gender, HttpServletResponse response,
			HttpServletRequest request) throws Exception {
		
		String url = "url is :";
		try {
			url = url + getRequestURLx(request);
		} catch (Exception e) {
			logger.warn(god.getTrace(e));
		}
		logger.info("-----" + url);
		SearchResult result = moodUserService.match(idxf, offset, limit,
				userId, gender);
		IOUtil.write(response, result.toJSON());
	}

	
	public String getRequestURLx(HttpServletRequest request) {
		
		  String urlx = request.getRequestURL().toString();
		  //http://localhost:10000/user/match.shtml  
		  //no catch param.
		  logger.info(urlx);
    String   url=request.getScheme()+"://";   
    url+=request.getHeader("host");   
    
    url+=request.getRequestURI();   
    if(request.getQueryString()!=null)   
          url+="?"+request.getQueryString();  
    return url;
	}
	// JAVA 获取完整URL 方法
	/**
	 * zafei
	 */
	public String getRequestURL(HttpServletRequest request) {
		if (request == null) {
			return "";
		}
		String url = "";
		url = request.getContextPath();
		url = url + request.getServletPath();

		java.util.Enumeration names = request.getParameterNames();
		int i = 0;
		if (!"".equals(request.getQueryString())
				|| request.getQueryString() != null) {
			url = url + "?" + request.getQueryString();
		}

		if (names != null) {
			while (names.hasMoreElements()) {
				String name = (String) names.nextElement();
				if (i == 0) {
					url = url + "?";
				} else {
					url = url + "&";
				}
				i++;

				String value = request.getParameter(name);
				if (value == null) {
					value = "";
				}

				url = url + name + "=" + value;
				try {
					// java.net.URLEncoder.encode(url, "ISO-8859");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		try {
			// String enUrl = java.net.URLEncoder.encode(url, "utf-8");
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return url;
	}

	@RequestMapping(value = "/api")
	/**cb23
	 * @author attilax 1466519819@qq.com
	 * @version  cb23
	 **/
	public void api(String op, String scheshpr, String id,
			HttpServletResponse response) throws Exception {
		fulltxtControllor4invoke c = new fulltxtControllor4invoke();
		c.writeToIndexSinglePerMessage(id, scheshpr);
		IOUtil.write(response, "ok");
	}

	public static void main(String[] args) throws ClassNotFoundException {
		// try {
		// Class.forName("org.logicalcobwebs.proxool.ProxoolDriver");
		// } catch (ClassNotFoundException e1) {
		//			 
		// e1.printStackTrace();
		// }
		iniProxool();
		// if (true)
		// return;
		MoodUserIndexService moodUserService = getbean();
		System.out.println(moodUserService);
		// com.mijie.core.CoreContextLoaderListener c=new
		// CoreContextLoaderListener();
		// MoodUserIndexService moodUserService=new MoodUserIndexService();

		// moodUserService. moodService=new MoodService();
		// moodUserService. moodService.dao=new MoodDao();
		SearchResult result = null;
		try {
			result = moodUserService.match("", 0, 15, 585115, 1);
		} catch (Exception e) {

			e.printStackTrace();
		}
		String s = result.toJSON();
		System.out.println(s);
	}

	private static MoodUserIndexService getbean() {
		ApplicationContext act = new FileSystemXmlApplicationContext(
				"classpath:applicationContext.xml");
		MoodUserIndexService moodUserService = (MoodUserIndexService) act
				.getBean("moodUserIndexService");
		return moodUserService;
	}
	
	public static Object getbean(String beanname ) {
		ApplicationContext act = new FileSystemXmlApplicationContext(
				"classpath:applicationContext.xml");
		Object moodUserService =  act
				.getBean(beanname);
		return moodUserService;
	}
	
	public static ApplicationContext getApplicationContext(String beanname ) {
		ApplicationContext act = new FileSystemXmlApplicationContext(
				"classpath:applicationContext.xml");
		 
		return act;
	}


	public static void iniProxool() {
		try {
			JAXPConfigurator
					.configure(
							PROXOOL_XML,
							false);
		} catch (ProxoolException e1) {

			e1.printStackTrace();
		}
		proxoolController.getnew();
	}

	private static void getProxool() throws ClassNotFoundException {
		Class.forName("org.logicalcobwebs.proxool.ProxoolDriver");
		// 2：创建数据库连接，这个参数是一个字符串，是数据源的别名，在配置文件中配置的timalias，参数格式为：proxool.数据源的别名
		Connection conn = null;
		try {
			conn = DriverManager.getConnection("proxool.maindb");
		} catch (SQLException e) {

			e.printStackTrace();
		}
		// conn.
		System.out.println(conn);

	}

}